package cn.v2tila.rsosa.management.service.serviceImpl;

import cn.v2tila.rsosa.management.entity.StudentEntity;
import cn.v2tila.rsosa.management.entity.ZpxxEntity;
import cn.v2tila.rsosa.management.jpa.ZpxxJPA;
import cn.v2tila.rsosa.management.service.ZpxxService;
import cn.v2tila.rsosa.management.utils.PageDataResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.*;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Optional;

/**
 * @author v2tila on 17:13 2019/4/18
 */
@Service
public class ZpxxServiceImpl implements ZpxxService {
    @Autowired
    private ZpxxJPA zpxxJPA;
    @Override
    public PageDataResult getZpxx(int page, int limit, ZpxxEntity zpxxEntity) {
        PageDataResult pageDataResult = new PageDataResult();
        Sort sort = new Sort(Sort.Direction.ASC, "id");
        Pageable pageable = PageRequest.of(page-1, limit, sort);

        ExampleMatcher matcher;

        if(zpxxEntity.getId()==0&&zpxxEntity.getCode()==-1){
            matcher = ExampleMatcher.matching()
                    .withMatcher("assoName", ExampleMatcher.GenericPropertyMatchers.contains())
                    .withIgnorePaths("id","assoId","hasDep","hasImgs","code");
        }else if(zpxxEntity.getCode()!=-1){
            matcher = ExampleMatcher.matching()
                    .withIgnorePaths("id","assoId","hasDep","hasImgs");
        }
        else{
            matcher = ExampleMatcher.matching()
                    .withIgnorePaths("assoId","hasDep","hasImgs","code");
        }
        Example<ZpxxEntity> example = Example.of(zpxxEntity,matcher);
        Page<ZpxxEntity> pages = zpxxJPA.findAll(example,pageable);
        List<ZpxxEntity> zpxxEntityList = pages.getContent();
        int count = zpxxJPA.findAll(example).size();
        pageDataResult.setData(zpxxEntityList);
        pageDataResult.setCount(count);
        return pageDataResult;
    }

    @Override
    public ZpxxEntity findById(int id) {
        Optional<ZpxxEntity> findResult = zpxxJPA.findById(id);
        return findResult.get();
    }

    @Override
    public ZpxxEntity saveAndFlush(ZpxxEntity zpxxEntity) {
        return zpxxJPA.saveAndFlush(zpxxEntity);
    }

    @Override
    public void deleteById(Integer id) {
        zpxxJPA.deleteById(id);
    }

}
